package com.example.productdataserviceprovider.controller;

import com.example.productdataserviceprovider.service.FileToExcelService;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Controller
public class FileToExcelController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private FileToExcelService service;

    @RequestMapping(value = "/index")
    public String indeGet(Model model) {

        return "file/index";
    }

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public void indePost(Model model, @RequestParam("dir") String dir, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File dirFile=new File(dir);
        if(!dirFile.exists()){
            response.getOutputStream().print(false);
        }else{
            File file = service.exportToExcel(dir);
            LocalDateTime time=LocalDateTime.now();
            DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String ymd=formatter.format(time);
            String fileName = "结果文件"+ymd+".xls";
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String agent = request.getHeader("User-Agent").toUpperCase(); //获得浏览器信息并转换为大写
            if (agent.indexOf("MSIE") > 0 || (agent.indexOf("GECKO") > 0 && agent.indexOf("RV:11") > 0)) {  //IE浏览器和Edge浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {  //其他浏览器
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            IOUtils.copy(new FileInputStream(file), out);
        }

    }
}
